﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

namespace Utility
{
    public abstract class MySqlServerHelper
    {
        /// <summary>
        /// mysql prefix ='?'
        /// </summary>
        private const char prefix = '?';

        /// <summary>
        ///Database connection strings
        /// </summary>
        private static readonly string connectionString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString;

        /// <summary>
        ///get page num
        /// </summary>
        private static readonly int PageNum = Convert.ToInt32(ConfigurationManager.AppSettings["pagenum"]);

        /// <summary>
        /// Hashtable to store cached parameters
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// use connectionString to create SqlConnection
        /// </summary>
        /// <returns>SqlConnection</returns>
        private static MySqlConnection GetConn()
        {

            switch (connectionString)
            {
                case "0":
                    //return new MySqlConnection("Host=10.10.103.163;User Id=module_web;Password=Abc@2022;Database=SAE_OFN;Respect Binary Flags=False;Default Command Timeout=120;Allow User Variables=True");
                    return new MySqlConnection("Host=DBSvr02.cloudlight.com.hk;User Id=module_web;Password=cl_module_web56;Database=SAE_OFN_EVALUATE;Respect Binary Flags=False;Default Command Timeout=120;Allow User Variables=True");

                case "1":
                    return new MySqlConnection("Host=DBSvr02.cloudlight.com.hk;User Id=module_web;Password=cl_module_web56;Database=SAE_OFN;Respect Binary Flags=False;Default Command Timeout=120;Allow User Variables=True");

            }
            return new MySqlConnection(connectionString);
          
        }

        /// <summary>
        /// CommandType.Text
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = GetConn())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    PrepareCommand(cmd, conn, trans, cmdType, cmdText, commandParameters);
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    trans.Commit();
                    return val;
                }
            }
        }

        /// <summary>
        /// CommandType.Text
        /// </summary>
        /// <param name="trans"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        private static int ExecuteNonQuery(MySqlTransaction trans, string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(trans, CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        private static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Batch DML
        /// </summary>
        /// <param name="sqls"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(IList<KeyValuePair<string, List<MySqlParameter>>> cmdTexts)
        {
            return ExecuteNonQuery(CommandType.Text, cmdTexts);
        }

        /// <summary>
        /// Batch DML
        /// </summary>
        /// <param name="cmdType"></param>
        /// <param name="sqls"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(CommandType cmdType, IList<KeyValuePair<string, List<MySqlParameter>>> cmdTexts)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = GetConn())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    int val = 0;

                    #region 
                    foreach (var item in cmdTexts)
                    {
                        MySqlParameter[] cmdParms = item.Value == null ? null : item.Value.ToArray();
                        PrepareCommand(cmd, conn, trans, cmdType, item.Key, cmdParms);
                        val += cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    } 
                    #endregion

                    trans.Commit();
                    return val;
                }
            }
        }

        /// <summary>
        /// CommandType.Text
        /// </summary>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static MySqlDataReader ExecuteReader(string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteReader(CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static MySqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();
            MySqlConnection conn = GetConn();

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// CommandType.Text
        /// </summary>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteScalar(CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();
            using (MySqlConnection conn = GetConn())
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataTable ExecuteDt(string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteDt(CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataTable ExecuteDt(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = GetConn())
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
                {
                    #region 
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    #endregion

                    #region 
                    //DataTable dt = new DataTable();
                    //sda.Fill(dt); 
                    #endregion
                    
                    cmd.Parameters.Clear();
                    return ds.Tables[0];
                }
            }
        }

        /// <summary>
        /// CommandType.Text
        /// </summary>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDs(string cmdText, params MySqlParameter[] commandParameters)
        {
            return ExecuteDs(CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDs(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = GetConn())
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    cmd.Parameters.Clear();
                    return ds;
                }
            }
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="cmd">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (MySqlParameter parm in cmdParms)
                {
                    DBUtils.MakeParm(parm, prefix);
                    cmd.Parameters.Add(parm);
                }
            }
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        private static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        private static MySqlParameter[] GetCachedParameters(string cacheKey)
        {
            MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            MySqlParameter[] clonedParms = new MySqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (MySqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }


     
    }
}
